/*****************************************************************************
Description:
This program runs MDRD2 and MDRD1 pscores at the program-level
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

args bw

* Settings
set trace off
set tracedepth 1
set more off

forval year = 2012/2014{

	* Save MDRD1 pscores as tempfile to merge in
	use "${cleandata}program_pscore_nobw_`year'.dta", clear
	keep stu prg_bkt pscore_form pscore_freq
	ren pscore_* pscore_*_no_bw
	tempfile nobw
	sa "`nobw'"

	* Start with MDRD2 (general risk) pscores
	use "${cleandata}program_pscore_`bw'`modification_str'_`year'.dta", clear

		* We are going to use the School DBN (District, Borough, Number) as
	* unique identifier for the school variable (sch)
	preserve
		keep final_disposition final_disposition_dbn
		duplicates drop
		ren final_disposition prg
		ren final_disposition_dbn sch_long
		tempfile dbns
		sa "`dbns'"
	restore
	merge m:1 prg using "`dbns'", keep(1 3)  gen(dbn_merge)

	* Merge in MDRD1 pscores
	merge 1:1 stu prg_bkt using "`nobw'", nogen

	* Checks for if we assign same program, then similarly for edopts
	gen same_prg = prg_offered == stripp

	gen prg_bkt_offered = prg_offered
	replace prg_bkt_offered = prg_offered + "_" + edopt_offered_suffix if edopt_offered_suffix != ""
	gen same_prg_bkt = prg_bkt_offered == ourmatch

	* Check missing lotto (is 0 by construction due to lotto simulation)
	gen missing_lotto = lottery_rank == .

	* Generate Ed. Opts. indicator
	gen edopts = edopt_r == 1 | edopt_s == 1

	* Screened use lottery, but not edopt
	gen screened_with_lottery_noedopt = screened_uses_lottery == 1 & description != "Ed. opt."

	* Generate indicator for number of offers by program
	bys stu prg : egen offer_prg = max(offer_mod)
	la var offer_prg "Indicator variable, = 1 if student got offer from program, 0 otherwise"

	// Merge in our simulated offers
	merge m:1 stu using "${cleandata}best_guess_simulated_match_`year'.dta", nogen keep(1 3) keepusing(ourmatch_noedops)

	// Generate offer variable for our match
	gen sim_offer_prg = prg == ourmatch_noedops

	// Aggegrate pscores for Ed.Opts. buckets by program
	foreach score in pscore_form pscore_form_bw pscore_form_no_bw ///
		pscore_freq pscore_freq_no_bw pscore_qbw  {
		bys stu prg : egen double `score'_prg = total( `score' )
	}

	keep stu prg sch_long desc offer_prg sim_offer_prg final_disposition_dbn pscore_form_prg ///
			pscore_*_prg choice missing_lotto same_prg same_prg_bkt screened_with_lottery_noedopt 
			 
	duplicates drop
	isid stu prg

	sa "${cleandata}/prg_level_pscores_`bw'_`year'.dta", replace

}
